﻿RulesManager = {
  service: "RouterRuleService.svc/",

  tabs: null,
  rules: {},
  data: null,
  ruleid: null,
  fval: null,

  valueLists: {},

  initialize: function () {
    this.tabs = $("#tabs").tabs();
    this.getRules();
    this.getValueLists();

    RulesManager.addHide();

    // reset the Create New Rule tab
    $('#tabs').bind('tabsselect', function (event, ui) {

        if (ui.index == 1)  // tab #2 (zero-based)
            $("#type").val("ContentKeywords").change();
    });

    $("#addRuleButton").button().click(function () {
      RulesManager.addRule();
      RulesManager.addHide();
    });

    $("#deleteRuleButton").button().click(function () {
      RulesManager.deleteRule();
      $("#dialog").dialog("close");
    });

    $("#modifyRuleButton").button().click(function () {
      RulesManager.modifyRule();
    });

    var that = this;

    $("#type").change(function (event) {
//         alert("in type change handler");
        if ($("#type").val() == "ContentKeywordFed") {
            $("#tfeduridiv").show();
            $("#tvaldiv").hide();
            $("#turidiv").hide();
        }
        else {
            $("#tfeduridiv").hide();
            $("#tvaldiv").show();
            $("#turidiv").show();
        }
    });

    $("#modtype").change(function (event) {
        // alert("in modtype change handler");
        if ($("#modtype").val() == "ContentKeywordFed") {
            $("#modtofeduridiv").show();
            $("#modtoval").hide();
            $("#modtouri").hide();
        }
        else {
            $("#modtofeduridiv").hide();
            $("#modtoval").show();
            $("#modtouri").show();
        }
    });

    $("#furi").change( function( event ){
      var uri = $(this).val();
      if( uri in that.valueLists ){
        that.populate( $("#fval"), that.valueLists[uri] );
      }
    });

    $("#turi").change( function( event ){
      var uri = $(this).val();
      if( uri in that.valueLists ){
        that.populate( $("#tval"), that.valueLists[uri] );
      }
    });

    $("#modfuri").change( function( event ){
      var uri = $(this).val();
      if( uri in that.valueLists ){
        that.populate( $("#modfval"), that.valueLists[uri] );
      }
    });

    $("#modturi").change( function( event ){
      var uri = $(this).val();
      if( uri in that.valueLists ){
        that.populate( $("#modtval"), that.valueLists[uri] );
      }
    });

  },

  // Populates a select element with the items from the specified list,
  // removing all existing items without the "Default" value.
  // If the "list" parameter is an object, the names of all fields will be
  // added to the select item
  populate: function( select, list ){

    select.find( ":not(option[value='Default'])" ).remove();

    var action = function( i, value ){
      select.append( $("<option></option>").text( value ) );
    };

    if( $.isArray( list ) ){
      $.each( list, action );
      
    } else {
      var i = 0;
      for( value in list ){
        action( i++, value );
      }
    }

  },

  addHide: function () {
    $("#dialog").hide();
  },

  getRules: function () {
    $.ajaxSetup({ cache: false });
    $.ajax({ url: this.service, context: this, success: this.loadRules });
  },

  loadRules: function (data, code, xhr) {
    this.rules = {};
    this.data = data;

    if ($.browser.msie) {
      try {

        for (var i = 0; i < data.childNodes[0].childNodes.length; i++) {
          var r = data.childNodes[0].childNodes[i];
          var rule = {
            id: r.childNodes[0].text,
            type: r.childNodes[1].text,
            fromURI: r.childNodes[2].text,
            fromValue: r.childNodes[3].text,
            toURI: r.childNodes[4].text,
            toValue: r.childNodes[5].text
          }
          this.rules[rule.id] = rule;

        }

      }
      catch (e) {
        this.log("loadRules error: " + e);
        this.rules = {};
      }

    }
    else {
      try {
        for (var i = 0; i < data.childNodes[0].childNodes.length; i++) {
          var r = data.childNodes[0].childNodes[i];
          var rule = {
            id: r.childNodes[0].textContent,
            type: r.childNodes[1].textContent,
            fromURI: r.childNodes[2].textContent,
            fromValue: r.childNodes[3].textContent,
            toURI: r.childNodes[4].textContent,
            toValue: r.childNodes[5].textContent
          }
          this.rules[rule.id] = rule;
        }
      }
      catch (e) {
        this.log("loadRules error: " + e);
        this.rules = {};
      }

    }



    this.displayRules();
  },

  displayRules: function () {

    $('#rulestable').html("");
    var html = $('#rulestable').html();
    html = "<tr><th>Rule</th><th>Type</th><th>From List URI</th><th>From List Value</th><th>To List URI</th><th>To List Value</th></tr>";
    var ct = 0;
    for (var r in this.rules) {
      ct = ct + 1;
      var rule = this.rules[r];
      html = html + "<tr id='" + rule.id + "'><td>" + ct + "</td><td>" + rule.type + "</td><td>" + rule.fromURI + "</td><td>" + rule.fromValue + "</td><td>" + rule.toURI + "</td><td>" + rule.toValue + "</td></tr>";
    }
    if (ct < 1) {
      html = "No Rules In Database.<br />Click Here to Add One.";
    }
    $('#rulestable').html(html);

    $(".striped tr").mouseover(function () { $(this).addClass("over"); }).mouseout(function () { $(this).removeClass("over"); });
    $(".striped tr:even").addClass("alt");

    var that = this;
    $("#rulestable tr").click(function (event) {

      var index = $('#rulestable tr').index(this);

      for (index in this.rules) {
        var selected = this.rules[index];
      }

      var td = $(this).closest('tr').children('td');


      ruleid = $(this).closest('tr').attr('id');

      //  alert("this is the ruleid: " + ruleid);

      var newtype = td.eq(1).text();
      var fromuri = td.eq(2).text();
      newfval = td.eq(3).text();
      var newturi = td.eq(4).text();
      var newtval = td.eq(5).text();

      that.populate( $("#modfuri"), that.valueLists );
      that.populate( $("#modturi"), that.valueLists );
      that.populate( $("#modfval"), that.valueLists[fromuri] );
      that.populate( $("#modtval"), that.valueLists[newturi] );
/*
      $.each( ["modfuri", "modturi", "modfval", "modtval"], function( i, id ){
        $("#" + id).find( ":not(option[value='Default'])" ).remove();
      });

      for( uri in that.valueLists ){
        $("#modfuri").append( $("<option></option>").text( uri ) );
        $("#modturi").append( $("<option></option>").text( uri ) );
      }

      $.each( that.valueLists[fromuri], function( i, value ){
        $("#modfval").append( $("<option></option>").text( value ) );
      });

      $.each( that.valueLists[newturi], function( i, value ){
        $("#modtval").append( $("<option></option>").text( value ) );
      });*/

      $("#modtype").val(newtype).change();
      $("#modfuri").val(fromuri);
      $("#modfval").val(newfval);
      $("#modturi").val(newturi);
      $("#modtofeduri").val(newturi);
      $("#modtval").val(newtval);

      $("#dialog").dialog({
        height: 600,
        width: 500,
        modal: true
      });

    });

  },

  // Gets ValueLists from the database
  getValueLists: function() {
    $.ajaxSetup({ cache: false });
    $.ajax({
      url: "ValueListService.svc/ValueList",
      context: this,
      success: this.loadValueLists
    });
  },


  // Loads ValueLists from the Ajax response
  loadValueLists: function(data, code, xhr) {
    this.valueLists = {};
    try {
              
      for(var i=0; i< data.childNodes[0].childNodes.length; i++) {
        var r = data.childNodes[0].childNodes[i];
        var l;

        if ($.browser.msie) {
          l = {
            id: r.childNodes[0].text,
            uri: r.childNodes[1].text,
            value: r.childNodes[2].text,
            cstruc: r.childNodes[3].text,
            desc: r.childNodes[4].text
          };
        } else {
          l = {
            id: r.childNodes[0].textContent,
            uri: r.childNodes[1].textContent,
            value: r.childNodes[2].textContent,
            cstruc: r.childNodes[3].textContent,
            desc: r.childNodes[4].textContent
          };
        } 

        this.addToValueLists( l );
      }

      $("#turi").find( ":not(option[value='Default'])" ).remove()

      for( uri in this.valueLists ){
        this.valueLists[uri].sort();
        $("#turi").append( $("<option></option>").text( uri ) );
      }

      $("#furi").change();


    } catch(e) {
      console.log("loadList error: " + e);
    }
  },

  // Adds an item to the cache for Value autocomplete
  addToValueLists: function( item ){
    if( !(item.uri in this.valueLists) ){
      this.valueLists[item.uri] = [];
    }

    if( item.value && item.value != "undefined" ){
      this.valueLists[item.uri].push( item.value );
    }
  },

  modifyRule: function (rule) {
    // alert("in modify");
    //Something wrong within the error 
    $("#modify").slideUp();
    var type = $("#modtype").val();
    var fromUri = $("#modfuri").val();
    var fromValue = $("#modfval").val();
    var fedUri = $("#modtofeduri").val();
    var toUri = $("#modturi").val();
    var toValue = $("#modtval").val();

    var error = this.validate( type, fromUri, fromValue, fedUri, toUri, toValue );
    
    if ( error ) {
      $('#modify').html(error).slideDown();
      return;
    }

    $("#dialog").dialog("close");

    if (type == "ContentKeywordFed") {
        toUri = $("#modtofeduri").val();
        toValue = "-";
    }
    else {
        toUri = $("#modturi").val();
        toValue = $("#modtval").val();
    }

    var xml = "<?xml version='1.0'?><RouterRule><RuleKey /><RuleType>" + type + "</RuleType><FromListURI>" + fromUri +
      "</FromListURI><FromListValue>" + fromValue + "</FromListValue>" +
      "<ToListURI>" + toUri + "</ToListURI><ToListValue>" + toValue + "</ToListValue></RouterRule>";

    $.ajax({ url: this.service + ruleid,
      context: this,
      type: 'POST',
      data: xml,
      processData: false,
      contentType: 'text/xml',
      success: this.modaddSuccess,
      error: this.addFail
    });
  },

  // Validates the supplied fields, and returns an error string. If
  // the input is valid, an empty string is returned
  validate: function( type, fromUri, fromValue, fedUri, toUri, toValue ){

    var error = "";

    if ( type == "Default") {
      error += "Rule Type cannot be blank<br />";
    }

    if ( fromUri == "Default") {
      error += "From List URI cannot be blank<br />";
    }

    if (fromValue == "Default") {
        error += "From List Value cannot be blank<br />";
    }

    if (type == "ContentKeywordFed") {
        if (fedUri == "") {
            error += "Federation URI Value cannot be blank<br />";
        }
    }
    else {
        if (toUri == "Default") {
            error += "To List URI cannot be blank<br />";
        }

        if (toValue == "Default") {
            error += "To List Value cannot be blank<br />";
        }
    }
    return error;

  },

  addRule: function (rule) {
    $("#error").slideUp();

    var type = $("#type").val();
    var fromUri = $("#furi").val();
    var fromValue = $("#fval").val();
    if ($("#type").val() == "ContentKeywordFed") {

//        alert($("#type").val());
        var toUri = $("#tfeduri").val();
        var toValue = "-";
    }
    else {
        var toUri = $("#turi").val();
        var toValue = $("#tval").val();
    }

    var error = this.validate( type, fromUri, fromValue, toUri, toValue );
    
    if ( error ) {
      $('#error').html(error).slideDown();
      return;
    }

    var xml = "<?xml version='1.0'?><RouterRule><RuleKey /><RuleType>" + type + "</RuleType><FromListURI>" + fromUri +
      "</FromListURI><FromListValue>" + fromValue + "</FromListValue>" +
      "<ToListURI>" + toUri + "</ToListURI><ToListValue>" + toValue + "</ToListValue></RouterRule>";

    $.ajax({ url: this.service,
      context: this,
      type: 'POST',
      data: xml,
      processData: false,
      contentType: 'text/xml',
      success: this.addSuccess,
      error: this.addFail
    });
  },

  modaddSuccess: function (data, code, xhr) {
    //    alert("Entered modaddSuccess");
    $(':input', '#modifiedform')
     .not(':button, :submit, :reset, :hidden')
     .val('')
     .removeAttr('checked')
     .removeAttr('selected');

    RulesManager.getRules();
    $(RulesManager.tabs).tabs('select', 0);
  },

  addSuccess: function (data, code, xhr) {
//         alert("Entered addSuccess");
    $(':input', '#rulesform')
     .not(':button, :submit, :reset, :hidden')
     .val('')
     .removeAttr('checked')
     .removeAttr('selected');

    RulesManager.getRules();
    $(RulesManager.tabs).tabs('select', 0);
  },

  addFail: function () {
    alert("Adding rule failed. Server error.");
  },

  deleteSuccess: function () {

    $(':input', '#modrulesform')
     .not(':button, :submit, :reset, :hidden')
     .val('')
     .removeAttr('checked')
     .removeAttr('selected');

    RulesManager.getRules();
    $(RulesManager.tabs).tabs('select', 0);

  },

  deleteFail: function () {
    alert("Deleting rule failed. Server error.");
  },

  deleteRule: function (data) {


    $.ajax({ url: this.service + ruleid,
      context: this,
      type: 'DELETE',
      data: data,
      processData: false,
      contentType: 'text/xml',
      success: this.deleteSuccess,
      error: this.deleteFail
    });

    //  alert("Deleted");
  }
};
